import React, { useEffect, useState } from 'react';
import './index.scss';
import { useNavigate } from 'react-router-dom';
import { ApiSignIn } from '../../../../api/sigin'
import Button from '../../../../components/Button';
import { InOrUpType, SignInType } from '../../type';
import { REGULAR_NAME, REGULAR_PASSWORD } from '../../../../constants/regular';
import { ResType } from '../../../../types/response';
import { sessionGet, sessionSet } from '../../../../utils/storage';
import Emitter from '../../../../utils/events';


// 登陆
function SignIn(_props: InOrUpType) {
  const navigate = useNavigate();
  const [info, setInfo] = useState<SignInType>({
    account: '',
    accountPromise: '',
    password: '',
    passwordPromise: '',
  });
  useEffect(() => {
    let sessionAccount = sessionGet('YH_WEB_FORM_ACCOUNT');
    let sessionPassword = sessionGet('YH_WEB_FORM_PASSWORD');
    let _info: SignInType = {
      account: sessionAccount || '',
      password: sessionPassword || '',
    }
    setInfo((i) => ({ ...i, ..._info }));
  }, [_props.inOrUp])

  // 验证
  const verify = () => {
    let _status: boolean = true,
      _info: SignInType = {
        accountPromise: '',
        passwordPromise: '',
      }
    if (!REGULAR_NAME.test(String(info.account))) {
      _info.accountPromise = '字母开头，长度4-12，允许字母数字下划线';
      _status = false;
    }
    if (!REGULAR_PASSWORD.test(String(info.password))) {
      _info.passwordPromise = '大小写字母数字组合，禁特殊字符，长度6-12';
      _status = false;
    }
    setInfo({ ...info, ..._info });
    return _status;
  }

  // 提交
  const submit = async () => {
    if (!verify()) return;
    let _data: SignInType = {
      account: info.account,
      password: info.password,
    }
    const _ApiSignIn: ResType = await ApiSignIn(_data);
    const { code, message } = _ApiSignIn;
    if (code !== 200) {
      Emitter.emit('toast', {
        message: message || '用户id生成失败',
      });
      return;
    }
    if (_ApiSignIn.code === 200) {
      sessionSet('YH_CUSTOMER_ID', _ApiSignIn.data.id || '');
      sessionSet('YH_WEB_FORM_ACCOUNT', info.account || '');
      sessionSet('YH_WEB_FORM_PASSWORD', info.password || '');
      navigate('/customer');
    } else {
      Emitter.emit('toast', {
        message: _ApiSignIn.message,
      });
    }
  };
  // 返回
  return (
    <div className="sign-in">
      <div className="row">
        <label htmlFor="signInAccount">用户名</label>
        <input
          id="signInAccount"
          className='input'
          type="text"
          placeholder="请输入用户名"
          autoComplete='off'
          onChange={({ target }) => {
            const obj: SignInType = { ...info, account: target.value }
            setInfo(obj)
          }}
        />
      </div>
      <div className="row">
        <div className='promise'>{info.accountPromise}</div>
      </div>
      <div className="row">
        <label htmlFor="signInPassword">密码</label>
        <input
          id="signInPassword"
          className='input'
          type="password"
          placeholder="请输入密码"
          autoComplete='off'
          onChange={({ target }) => {
            const obj: SignInType = { ...info, password: target.value }
            setInfo(obj)
          }}
        />
      </div>
      <div className="row">
        <div className='promise'>{info.passwordPromise}</div>
      </div>
      <div className="row">
        <Button
          text='登录'
          size="large"
          handle={() => submit()}
        />
      </div>
    </div>
  );
}

export default SignIn;